package com.tl.commonlibrary.network;

import com.google.gson.Gson;
import com.tl.commonlibrary.network.bean.base.Data;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/6/5 0005.
 * http://blog.csdn.net/spinchao/article/details/52932145
 * 请求拦截器
 */

public class RequestInterceptor implements Interceptor {
    CommonParam commonParam;

    public RequestInterceptor(CommonParam param) {
        this.commonParam = param;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (request.method().equalsIgnoreCase("post")) {
            if (request.body() instanceof FormBody) {
                FormBody.Builder builder = new FormBody.Builder();
                FormBody body = (FormBody) request.body();
                Data data = new Data();
                HashMap<String, String> map = new HashMap<>();
                for (int i = 0; i < body.size(); i++) {
                    map.put(body.encodedName(i), body.encodedValue(i));
                }
                data.body = new Gson().toJsonTree(map);
                body = builder.addEncoded("data", new Gson().toJson(data)).build();
                request = request.newBuilder().post(body).build();
            }
        }else if (request.method().equalsIgnoreCase("GET")) {
            //添加公共参数
            HttpUrl httpUrl = request.url()
                    .newBuilder()
                    .addQueryParameter("clienttype","1")
                    .addQueryParameter("imei", "imei")
                    .addQueryParameter("version", "VersionName")
                    .addQueryParameter("timestamp", String.valueOf(System.currentTimeMillis()))
                    .build();
            request = request.newBuilder().url(httpUrl).build();

        }
        return chain.proceed(request);
    }

}
